<template>
  <div class="report-container">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true">
        <el-form-item label="统计维度" prop="dimension">
          <el-select v-model="searchForm.dimension" placeholder="请选择统计维度" style="width: 180px">
            <el-option label="按日统计" value="DAY" />
            <el-option label="按周统计" value="WEEK" />
            <el-option label="按月统计" value="MONTH" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="equipmentType">
          <el-select v-model="searchForm.equipmentType" placeholder="请选择设备类型" clearable style="width: 180px">
            <el-option label="生产设备" value="PRODUCTION" />
            <el-option label="检测设备" value="TESTING" />
            <el-option label="辅助设备" value="AUXILIARY" />
          </el-select>
        </el-form-item>
        <el-form-item label="车间" prop="workshop">
          <el-select v-model="searchForm.workshop" placeholder="请选择车间" clearable style="width: 180px">
            <el-option label="装配车间" value="ASSEMBLY" />
            <el-option label="机加车间" value="MACHINING" />
            <el-option label="包装车间" value="PACKAGING" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">导出报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value equipment-count">{{ statsData.totalEquipment }}</div>
              <div class="stat-label">设备总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value utilization-rate">{{ statsData.utilizationRate }}%</div>
              <div class="stat-label">设备利用率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value oee">{{ statsData.oee }}%</div>
              <div class="stat-label">OEE综合效率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value mtbf">{{ statsData.mtbf }}h</div>
              <div class="stat-label">平均故障间隔</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>设备利用率趋势</span>
              </div>
            </template>
            <div ref="utilizationTrendChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>设备状态分布</span>
              </div>
            </template>
            <div ref="statusDistributionChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>故障统计</span>
              </div>
            </template>
            <div ref="faultStatisticsChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>维护成本趋势</span>
              </div>
            </template>
            <div ref="maintenanceCostChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>设备运行明细</span>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="equipmentCode" label="设备编码" />
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="workshop" label="车间" />
        <el-table-column prop="runningTime" label="运行时间(h)" align="right" />
        <el-table-column prop="idleTime" label="空闲时间(h)" align="right" />
        <el-table-column prop="faultTime" label="故障时间(h)" align="right">
          <template #default="scope">
            <span class="fault-time" v-if="scope.row.faultTime > 0">{{ scope.row.faultTime }}</span>
            <span v-else>0</span>
          </template>
        </el-table-column>
        <el-table-column prop="utilizationRate" label="利用率" align="right">
          <template #default="scope">
            <span :class="getUtilizationRateClass(scope.row.utilizationRate)">{{ scope.row.utilizationRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="oee" label="OEE" align="right">
          <template #default="scope">
            <span :class="getOeeClass(scope.row.oee)">{{ scope.row.oee }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceCost" label="维护成本" align="right">
          <template #default="scope">
            ¥{{ scope.row.maintenanceCost }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="equipmentReport">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import * as echarts from "echarts";

const loading = ref(false);
const tableData = ref([]);
const searchFormRef = ref<FormInstance>();

// 图表引用
const utilizationTrendChart = ref();
const statusDistributionChart = ref();
const faultStatisticsChart = ref();
const maintenanceCostChart = ref();

// 查询表单
const searchForm = reactive({
  dimension: "DAY",
  dateRange: [],
  equipmentType: "",
  workshop: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 统计数据
const statsData = reactive({
  totalEquipment: 156,
  utilizationRate: 85.6,
  oee: 78.3,
  mtbf: 168
});

// 获取利用率样式
const getUtilizationRateClass = (rate: number) => {
  if (rate >= 90) return "rate-excellent";
  if (rate >= 80) return "rate-good";
  if (rate >= 70) return "rate-normal";
  return "rate-poor";
};

// 获取OEE样式
const getOeeClass = (oee: number) => {
  if (oee >= 85) return "rate-excellent";
  if (oee >= 75) return "rate-good";
  if (oee >= 65) return "rate-normal";
  return "rate-poor";
};

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 设备利用率趋势图
    if (utilizationTrendChart.value) {
      const trendChart = echarts.init(utilizationTrendChart.value);
      const trendOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['设备利用率', 'OEE'] },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: { type: 'value', max: 100 },
        series: [
          {
            name: '设备利用率',
            type: 'line',
            data: [82.5, 85.2, 83.8, 86.1, 84.7, 85.6]
          },
          {
            name: 'OEE',
            type: 'line',
            data: [75.2, 78.1, 76.8, 79.5, 77.2, 78.3]
          }
        ]
      };
      trendChart.setOption(trendOption);
    }

    // 设备状态分布图
    if (statusDistributionChart.value) {
      const statusChart = echarts.init(statusDistributionChart.value);
      const statusOption = {
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [
          {
            name: '设备状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 120, name: '运行中' },
              { value: 25, name: '空闲' },
              { value: 8, name: '故障' },
              { value: 3, name: '维护中' }
            ]
          }
        ]
      };
      statusChart.setOption(statusOption);
    }

    // 故障统计图
    if (faultStatisticsChart.value) {
      const faultChart = echarts.init(faultStatisticsChart.value);
      const faultOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['故障次数', '故障时长'] },
        xAxis: {
          type: 'category',
          data: ['机械故障', '电气故障', '液压故障', '控制故障', '其他故障']
        },
        yAxis: [
          { type: 'value', name: '故障次数' },
          { type: 'value', name: '故障时长(h)' }
        ],
        series: [
          {
            name: '故障次数',
            type: 'bar',
            data: [12, 8, 5, 3, 2]
          },
          {
            name: '故障时长',
            type: 'line',
            yAxisIndex: 1,
            data: [24, 16, 10, 6, 4]
          }
        ]
      };
      faultChart.setOption(faultOption);
    }

    // 维护成本趋势图
    if (maintenanceCostChart.value) {
      const costChart = echarts.init(maintenanceCostChart.value);
      const costOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['预防性维护', '故障维修', '备件成本'] },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: { type: 'value' },
        series: [
          {
            name: '预防性维护',
            type: 'bar',
            stack: '总量',
            data: [15000, 18000, 16000, 17000, 19000, 16500]
          },
          {
            name: '故障维修',
            type: 'bar',
            stack: '总量',
            data: [8000, 6000, 9000, 5000, 7000, 6500]
          },
          {
            name: '备件成本',
            type: 'bar',
            stack: '总量',
            data: [12000, 14000, 13000, 15000, 11000, 13500]
          }
        ]
      };
      costChart.setOption(costOption);
    }
  });
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        date: "2024-01-15",
        equipmentCode: "EQ001",
        equipmentName: "数控机床A1",
        workshop: "机加车间",
        runningTime: 18.5,
        idleTime: 4.5,
        faultTime: 1.0,
        utilizationRate: 77.1,
        oee: 72.5,
        maintenanceCost: 1200
      },
      {
        date: "2024-01-15",
        equipmentCode: "EQ002",
        equipmentName: "装配线B1",
        workshop: "装配车间",
        runningTime: 22.0,
        idleTime: 2.0,
        faultTime: 0,
        utilizationRate: 91.7,
        oee: 88.2,
        maintenanceCost: 800
      }
    ];
    
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取设备报表数据失败:", error);
    ElMessage.error("获取设备报表数据失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 导出报表
const handleExport = () => {
  ElMessage.info("导出设备报表功能开发中");
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
  initCharts();
});
</script>

<style scoped>
.report-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.equipment-count {
  color: #409eff;
}

.utilization-rate {
  color: #67c23a;
}

.oee {
  color: #e6a23c;
}

.mtbf {
  color: #f56c6c;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.fault-time {
  color: #f56c6c;
  font-weight: bold;
}

.rate-excellent {
  color: #67c23a;
  font-weight: bold;
}

.rate-good {
  color: #409eff;
  font-weight: bold;
}

.rate-normal {
  color: #e6a23c;
  font-weight: bold;
}

.rate-poor {
  color: #f56c6c;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>